import axios from 'axios'
import { throwErr } from '@/components/utils'
import store from '@/components/store'
import { Message } from 'element-ui'
import router from '@/router'
import * as s from '@/components/utils/sessionStorage'

//过滤请求
axios.interceptors.request.use(config => {
  config.timeout = 20 * 1000
  return config
}, error => {
  return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    return Promise.resolve(response)
    if (response.status==200) {
      return Promise.resolve(response.data)
    } else{
      store.dispatch('setMenu', {})
      Message({
        message: '登录过期'
      })
      router.push('/login')
      return Promise.reject(response.data)
    } 
  },
  error => {
    if (error && error.response) {
      let res = {}
      res.code = error.response.status
      res.msg = throwErr(error.response.status, error.response)
      return Promise.reject(res)
    }
    return Promise.reject(error)
  }
)
export default function request(method, url, data) {
  method = method.toLocaleLowerCase() // 把所有大写都换成小写
  if (method == 'post') {
    return axios.post(url, data, {
      baseURL: 'http://192.168.0.152:8084',
      headers: {
        'Content-Type': 'application/json',
        'set_cookie':'token='+ s.get('token')
      }
    })
  } else if (method == 'get') {
    return axios.get(url, {
      // baseURL: 'https://www.easy-mock.com/mock/5bf36e66975b25624d2c59f3/api/szy',
      baseURL: 'http://192.168.0.152:8084',
      headers: {
        'Content-Type': 'application/json',
        'set_cookie':'token='+ s.get('token')
      },
      params: data
    })
  } else if (method == 'delete') {
    return axios.delete(url, {
      params: data
    })
  }else if(method=='put'){
    return axios.put(url, data, {
      baseURL: 'http://192.168.0.152:8084',
      headers: {
        'Content-Type': 'application/json',
        'set_cookie':'token='+ s.get('token')
      }
    })
  }
}

